package com.water76016.ourtask.controller;

import com.water76016.ourtask.common.RestResult;
import com.water76016.ourtask.entity.Files;
import com.water76016.ourtask.service.FileService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {

        @Value("${filepath}")
        private String filepath;

        @Autowired
        private FileService fileService;

        /**
         * 处理文件上传
         */
        @PostMapping(value = "/upload")
        public String uploading(@RequestParam("file") MultipartFile file , Integer userId) {
            File targetFile = new File(filepath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try (FileOutputStream out = new FileOutputStream(filepath + new Date() + "\\" + file.getOriginalFilename());){
                out.write(file.getBytes());
                Files files = Files.builder()
                        .userId(userId)
                        .fileName(file.getOriginalFilename())
                        .filePath(filepath + new Date() + "\\" + file.getOriginalFilename())
                        .fileSize(file.getSize())
                        .build();
                fileService.saveOrUpdate(files);

            } catch (Exception e) {
                e.printStackTrace();
                //log.error("文件上传失败!");
                return "uploading failure";
            }
            //log.info("文件上传成功!");
            return "uploading success";
        }

        @RequestMapping("/download")
        public void downLoad(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
            File file = new File(filepath + new Date() + "\\" + fileName );
            if(file.exists()){
                response.setContentType("application/octet-stream");
                response.setHeader("content-type", "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"utf8"));
                byte[] buffer = new byte[1024];
                //输出流
                OutputStream os = null;
                try(FileInputStream fis= new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis);) {
                    os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while(i != -1){
                        os.write(buffer);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @ApiOperation("展示文件列表")
        @RequestMapping("/filelist")
        public RestResult getFileList(Integer userId){
            QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            List<Files> filesList = fileService.list(queryWrapper);
            return RestResult.success(filesList);
        }
    }

